﻿using Abp.Events.Bus;
using Abp.Modules;
using Abp.Reflection.Extensions;
using AbpProjectTemplate.Components.Configuration;
using AbpProjectTemplate.EntityFrameworkCore;
using AbpProjectTemplate.Migrator.DependencyInjection;
using Castle.MicroKernel.Registration;
using Microsoft.Extensions.Configuration;

namespace AbpProjectTemplate.Migrator
{
    [DependsOn(typeof(AppEntityFrameworkModule))]
    public class AppMigratorModule : AbpModule
    {
        private readonly IConfigurationRoot _appConfiguration;

        public AppMigratorModule(AppEntityFrameworkModule appEntityFrameworkModule)
        {
            appEntityFrameworkModule.SkipDbSeed = true;

            this._appConfiguration = AppConfigurations.Get(
                typeof(AppMigratorModule).GetAssembly().GetDirectoryPathOrNull()
            );
        }

        public override void PreInitialize()
        {
            this.Configuration.DefaultNameOrConnectionString = this._appConfiguration.GetConnectionString(
                AppConsts.ConnectionStringName
            );

            this.Configuration.BackgroundJobs.IsJobExecutionEnabled = false;
            this.Configuration.ReplaceService(
                typeof(IEventBus),
                () => this.IocManager.IocContainer.Register(
                    Component.For<IEventBus>().Instance(NullEventBus.Instance)
                )
            );
        }

        public override void Initialize()
        {
            this.IocManager.RegisterAssemblyByConvention(typeof(AppMigratorModule).GetAssembly());
            ServiceCollectionRegistrar.Register(this.IocManager);
        }
    }
}

